package com.zsix.system.service.impl;

import com.zsix.common.dto.base.SearchPage;
import com.zsix.common.entity.process.ProcessEntity;
import com.zsix.common.util.StringUtils;
import com.zsix.system.mapper.processDefinitionMapper.EventClassMapper;
import com.zsix.system.mapper.processDefinitionMapper.ProcessParamsMapper;
import com.zsix.system.mapper.processDefinitionMapper.RuleOverDueMapper;
import com.zsix.system.mapper.processDefinitionMapper.TimedStartMapper;
import com.zsix.system.mapper.processMapper.FlowEntityMapper;
import com.zsix.system.mapper.processMapper.FlowSortMapper;
import com.zsix.system.mapper.processMapper.ProcessEntityMapper;
import com.zsix.system.mapper.taskAssigneeMapper.FlowElementAttrsMapper;
import com.zsix.system.mapper.taskAssigneeMapper.OvProcessInstanceMapper;
import com.zsix.system.service.IProcessDefinitionService;
import com.zsix.system.service.manager.ProcessDefinitionManager;
import com.zsix.system.service.manager.MapperManager;
import com.zsix.common.dto.controllerParams.*;
import com.zsix.common.entity.process.FlowEntity;
import com.zsix.common.entity.process.FlowEnum;
import com.zsix.common.entity.process.FlowSort;
import com.zsix.common.entity.taskAssignee.FlowElementAttrs;
import com.zsix.common.entity.taskAssignee.OvProcessInstance;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.*;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ProcessDefinitionServiceImpl implements IProcessDefinitionService {
    @Autowired //流程部署服务
    private RepositoryService repositoryService;
    @Autowired
    private OvProcessInstanceMapper ovProcessInstanceMapper;
    @Autowired //流程分类服务
    private FlowSortMapper flowSortMapper;
    @Autowired //流程定义自定义服务
    private FlowEntityMapper flowEntityMapper;
    @Autowired
    private FlowElementAttrsMapper flowElementAttrsMapper;
    @Autowired
    private EventClassMapper eventClassMapper;
    @Autowired
    private ProcessParamsMapper processParamsMapper;
    @Autowired
    private ProcessEntityMapper processEntityMapper;
    @Autowired
    private RuleOverDueMapper ruleOverDueMapper;
    @Autowired
    private TimedStartMapper timedStartMapper;
    @Autowired
    private ProcessDefinitionManager iProcessDefinitionManager;
    @Autowired
    private MapperManager mapperManager;


    /**
     * 获取流程部署列表
     * @param deploymentInfo
     * @return
     */
    @Override
    public HashMap<String ,Object> getDeployment(DeploymentInfo deploymentInfo){
        int startIndex=(deploymentInfo.getPageNum()-1)*deploymentInfo.getPageSize();
        int maxIndex=deploymentInfo.getPageSize();

        //流程定义总数量
        List<ProcessDefinition> processDefinitionlist = repositoryService.createProcessDefinitionQuery()
                .latestVersion()
                .list();

        List<HashMap<String, Object>> listMap= new ArrayList<HashMap<String, Object>>();
        List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery()
                .latestVersion()
                .listPage(startIndex,maxIndex);

        list.sort((y,x)->x.getVersion()-y.getVersion());

        for (ProcessDefinition pd : list) {
            if(!StringUtils.isEmpty(deploymentInfo.getSortId()))
            {
                if(!deploymentInfo.getSortId().equals(pd.getEngineVersion()))
                    continue;
            }
            HashMap<String, Object> hashMap = new HashMap<>();
            //流程定义id
            hashMap.put("procId", pd.getId());
            //流程定义名称
            hashMap.put("name", pd.getName());
            //流程key
            hashMap.put("procKey", pd.getKey());
            //resourceName
            hashMap.put("resourceName", pd.getResourceName());
            //流程部署ID
            hashMap.put("deploymentID", pd.getDeploymentId());
            hashMap.put("flowSort",pd.getEngineVersion());
            //版本
            hashMap.put("version", pd.getVersion());
            listMap.add(hashMap);
        }
        HashMap<String ,Object> hashMap=new HashMap<>();
        hashMap.put("list",listMap);
        hashMap.put("total",processDefinitionlist.size());
        return hashMap;
    }
    /**
     * 获取流程模板
     * @param deploymentId
     */
    @Override
    public void getDeploymentXmlById(HttpServletResponse response, String deploymentId){
        try {
            InputStream inputStream = repositoryService.getResourceAsStream(deploymentId,"createWithBPMNJS.bpmn");
            int count = inputStream.available();
            byte[] bytes = new byte[count];
            response.setContentType("text/xml");
            OutputStream outputStream = response.getOutputStream();
            while (inputStream.read(bytes) != -1) {
                outputStream.write(bytes);
            }
            inputStream.close();
        } catch (Exception e) {
            e.toString();
        }
    }
    /**
     * 发布流程
     * @param BPMNXml
     * @return
     */
    @Override
    public String deployWithBPMNJS(String BPMNXml){
        Deployment deployment = repositoryService.createDeployment()
                .addString("createWithBPMNJS.bpmn",BPMNXml)
                .deploy();

        iProcessDefinitionManager.createTask(deployment.getId());
        return deployment.getId();
    }

    /**
     * 更新业务配置
     * @param params
     * @return
     */
    @Override
    public String updateDeployment(ProcessDefinitionParams params){
        //更新流程部署信息，将引擎版本号作为流程类别
        FlowEntity flowEntity=new FlowEntity();
        flowEntity.setId_(params.getId());
        flowEntity.setProcessKey(params.getKey());
        flowEntity.setEngine_version_(params.getSortid());
        flowEntity.setName_(params.getName());
        flowEntityMapper.updateFlowEntity(flowEntity);

        //更新表单信息
        OvProcessInstance ovProcessInstance=ovProcessInstanceMapper.getProcessInsByDeployId(params.getId());
        FlowElementAttrs flowElementAttrs=new FlowElementAttrs();
        BeanUtils.copyProperties(params,flowElementAttrs);
        flowElementAttrs.setProcess_key(ovProcessInstance.getKey_());
        flowElementAttrsMapper.updateFlowMap(flowElementAttrs);

        //设置流程参数
        List<ProceParams> proceParamsList=params.getProceParams();
        if(proceParamsList!=null){
            if(proceParamsList.size()>0){
                processParamsMapper.deleteProceParams(params.getKey());
                List<ProceParams> newProceParamsList=new ArrayList<>();
                for(ProceParams item:proceParamsList){
                    item.setMypk(UUID.randomUUID().toString());
                    item.setProcessKey(params.getKey());
                    newProceParamsList.add(item);
                }
                processParamsMapper.setProceParams(newProceParamsList);
            }
        }
        //设置流程事件
        List<EventClass> eventClassList=params.getEventClass();
        eventClassMapper.deleteEventClass(params.getKey());
        //设置主键
        List<EventClass> newEventClassList=new ArrayList<>();
        for(EventClass item:eventClassList){
            item.setMypk(UUID.randomUUID().toString());
            item.setTargetId(params.getKey());
            newEventClassList.add(item);
        }
        eventClassMapper.setEventClass(newEventClassList);
        //设置流程逾期
        RuleOverDue ruleOverDue=params.getRuleOverDue();
        ruleOverDue.setTargetId(params.getKey());
        ruleOverDueMapper.deleteRuleOverDue(params.getKey());
        ruleOverDue.setMypk(UUID.randomUUID().toString());
        ruleOverDueMapper.setRuleOverDue(ruleOverDue);
        //设置流程定时发起
        TimedStart timedStart=params.getTimedStart();
        timedStart.setProcessKey(params.getKey());
        timedStartMapper.deleteTimedStart(params.getKey());
        timedStart.setMypk(UUID.randomUUID().toString());
        timedStartMapper.setTimedStart(timedStart);

        //设置节点信息
        List<TaskDefinitionParams> taskDefinitionParams=params.getUserTasks();
        for(TaskDefinitionParams taskParams:taskDefinitionParams){
            //节点功能设置
            TaskModel taskModel=taskParams.getFormModel();
            FlowElementAttrs taskElementAttrs=new FlowElementAttrs();
            BeanUtils.copyProperties(taskModel,taskElementAttrs);
            taskElementAttrs.setTask_def_key(taskParams.getId());
            taskElementAttrs.setProcess_key(params.getKey());
            taskElementAttrs.setRefuse(taskModel.getRefuse());
            taskElementAttrs.setEndTask(taskModel.getEndTask());
            taskElementAttrs.setCountersign(taskModel.getCountersign());
            taskElementAttrs.setTransfer(taskModel.getTransfer());
            flowElementAttrsMapper.updateFlowElementAttrs(taskElementAttrs);

            //设置节点事件
            List<EventClass> taskEventClass=taskParams.getEventClass();
            eventClassMapper.deleteEventClass(taskParams.getId());
            List<EventClass> newTaskEventClass=new ArrayList<>();
            for(EventClass item:taskEventClass){
                item.setMypk(UUID.randomUUID().toString());
                item.setTargetId(taskParams.getId());
                newTaskEventClass.add(item);
            }
            eventClassMapper.setEventClass(newTaskEventClass);

            //节点逾期设置
            RuleOverDue taskRuleOverDue=taskParams.getRuleOverDue();
            taskRuleOverDue.setTargetId(taskParams.getId());
            ruleOverDueMapper.deleteRuleOverDue(taskParams.getId());
            taskRuleOverDue.setMypk(UUID.randomUUID().toString());
            ruleOverDueMapper.setRuleOverDue(taskRuleOverDue);
        }

        return "执行成功";
    }
    /**
     * 获取流程属性配置   old
     * @param process_key
     * @return
     */
    @Override
    public HashMap<String,Object> getFormElement(String process_key){
        HashMap<String,Object> hashMap=new HashMap<>();
        //获取流程模版信息
        OvProcessInstance ovProcessInstance=ovProcessInstanceMapper.getProcessInsLastVersion(process_key);
        BpmnModel bpmnModel = repositoryService.getBpmnModel(ovProcessInstance.getId_());
        //获取流程信息
        Process process=bpmnModel.getProcesses().get(0);
        StartEvent startEvent=(StartEvent)process.getInitialFlowElement();
        List<SequenceFlow> outgoingFlows = startEvent.getOutgoingFlows();
        //获取UserTask类型数据
        UserTask userTask = (UserTask) outgoingFlows.get(0).getTargetFlowElement();

        List<HashMap<String,Object>> userTasks=new ArrayList<>();
        Collection<FlowElement> flowElements=process.getFlowElements();

        for(FlowElement flowElement:flowElements){
            if(flowElement instanceof UserTask){
                //节点属性
                UserTask ut=(UserTask) flowElement;
                HashMap<String,Object> userTaskMap=new HashMap<>();
                //基本信息
                HashMap<String,Object> baseClass=new HashMap<>();
                //事件信息
                List<HashMap<String,Object>> eventClassList=new ArrayList<>();
                List<EventClass> eventList=eventClassMapper.getEventClass(ut.getId());
                if(eventList.size()==0){
                    for(int i=0;i<9;i++) {
                        HashMap<String,Object> eventClass=new HashMap<>();
                        eventClass.put("eventType", String.valueOf(i));
                        eventClass.put("eventWay", "0");
                        eventClass.put("eventDoc", "");
                        eventClassList.add(eventClass);

                    }
                    userTaskMap.put("eventClass", eventClassList);
                }
                else{
                    userTaskMap.put("eventClass", eventList);
                }
                //逾期信息
                RuleOverDue ruleOverDue=ruleOverDueMapper.getRuleOverDue(ut.getId());
                if(ruleOverDue==null) {
                    HashMap<String, Object> ruleOverDueMap = new HashMap<>();
                    //逾期信息
                    ruleOverDueMap.put("actionCycle", "");
                    ruleOverDueMap.put("beforeTime", "");
                    ruleOverDueMap.put("overDueWar", "0");
                    ruleOverDueMap.put("overDueWarUrl", "");
                    ruleOverDueMap.put("overDueWay", "0");
                    ruleOverDueMap.put("overDueWayUrl", "");
                    userTaskMap.put("ruleOverDue", ruleOverDueMap);
                }
                else{
                    userTaskMap.put("ruleOverDue", ruleOverDue);
                }

                userTaskMap.put("id",ut.getId());
                userTaskMap.put("name",ut.getName());
                //功能设置
                FlowElementAttrs taskElementAttrs=flowElementAttrsMapper.getFlowElementAttrs(ut.getId());
                baseClass.put("returnWay",taskElementAttrs.getReturnWay());
                baseClass.put("runWay",taskElementAttrs.getRunWay());
                baseClass.put("transfer",taskElementAttrs.getTransfer().toString());
                baseClass.put("countersign",taskElementAttrs.getCountersign().toString());
                baseClass.put("jumpWay",taskElementAttrs.getJumpWay());
                baseClass.put("endTask",taskElementAttrs.getEndTask().toString());
                baseClass.put("refuse",taskElementAttrs.getRefuse().toString());
                baseClass.put("ccWay",taskElementAttrs.getCcWay());
                baseClass.put("autoCCWay",taskElementAttrs.getAutoCCWay());
                userTaskMap.put("formModel",baseClass);

                userTasks.add(userTaskMap);
            }
        }
        //流程信息
        FlowElementAttrs flowElementAttrs=flowElementAttrsMapper.getFlowElementAttrs(userTask.getId());
        //流程参数
        List<ProceParams> processParams=processParamsMapper.getProceParams(process_key);
        //流程逾期信息
        RuleOverDue proRuleOverDue=ruleOverDueMapper.getRuleOverDue(process_key);
        if(proRuleOverDue==null) {
            HashMap<String, Object> ruleOverDueMap = new HashMap<>();
            //逾期信息
            ruleOverDueMap.put("actionCycle", "");
            ruleOverDueMap.put("beforeTime", "");
            ruleOverDueMap.put("overDueWar", "0");
            ruleOverDueMap.put("overDueWarUrl", "");
            ruleOverDueMap.put("overDueWay", "0");
            ruleOverDueMap.put("overDueWayUrl", "");
            hashMap.put("ruleOverDue",ruleOverDueMap);
        }
        else{
            hashMap.put("ruleOverDue",proRuleOverDue);
        }
        //定时启动
        TimedStart timedStart=timedStartMapper.getTimedStart(process_key);
        if(timedStart==null) {
            HashMap<String, Object> timedStartMap = new HashMap<>();
            //定时启动信息
            timedStartMap.put("tstWay", "");
            timedStartMap.put("tstDoc", "");
            timedStartMap.put("userSql", "");
            hashMap.put("timedStart",timedStartMap);
        }
        else{
            hashMap.put("timedStart",timedStart);
        }
        //流程事件
        List<HashMap<String,Object>> procEventClassList=new ArrayList<>();
        List<EventClass> procEventList=eventClassMapper.getEventClass(process_key);
        if(procEventList.size()==0){
            for(int i=0;i<3;i++) {
                HashMap<String,Object> eventClass=new HashMap<>();
                eventClass.put("eventType", String.valueOf(i));
                eventClass.put("eventWay", "0");
                eventClass.put("eventDoc", "");
                procEventClassList.add(eventClass);
            }
            hashMap.put("eventClass",procEventClassList);
        }
        else{
            hashMap.put("eventClass",procEventList);
        }
        hashMap.put("userTasks",userTasks);
        hashMap.put("flowElementAttrs",flowElementAttrs);
        hashMap.put("proceParams",processParams);
        return hashMap;
    }

    /**
     * 流程属性
     * @param process_key
     * @return
     */
    @Override
    public ProcessDefinitionParams processProperties(String process_key){
        ProcessDefinitionParams params=new ProcessDefinitionParams();
        //获取流程模版信息
        OvProcessInstance ovProcessInstance=mapperManager.ovProcessInstance(process_key);
        if(ovProcessInstance==null){
            return iProcessDefinitionManager.getParams(process_key);
        }
        else {
            BpmnModel bpmnModel = repositoryService.getBpmnModel(ovProcessInstance.getId_());
            //获取流程信息
            Process process = bpmnModel.getProcesses().get(0);
            //流程业务分类
            params.setSortid(ovProcessInstance.getEngine_version_());
            try {
                StartEvent startEvent = (StartEvent) process.getInitialFlowElement();
                List<SequenceFlow> outgoingFlows = startEvent.getOutgoingFlows();
                //获取UserTask类型数据
                UserTask userTask = (UserTask) outgoingFlows.get(0).getTargetFlowElement();
                //流程信息
                FlowElementAttrs flowElementAttrs = flowElementAttrsMapper.getFlowElementAttrs(userTask.getId());
                //标题生成规则
                params.setTitleModel(flowElementAttrs.getTitleModel());
            }
            catch (Exception ex){
                //标题生成规则
                params.setTitleModel("");
            }
        }
        //流程参数
        List<ProceParams> processParams=Optional.ofNullable(processParamsMapper.getProceParams(process_key))
                .orElseGet(()->new ArrayList<>());
        params.setProceParams(processParams);
        //流程逾期信息
        RuleOverDue proRuleOverDue=Optional.ofNullable(mapperManager.ruleOverDue(process_key))
                .orElseGet(()->iProcessDefinitionManager.createRuleOverDue());
        params.setRuleOverDue(proRuleOverDue);
        //定时启动
        TimedStart timedStart=Optional.ofNullable(timedStartMapper.getTimedStart(process_key))
                .orElseGet(()->iProcessDefinitionManager.createTimedStart());
        params.setTimedStart(timedStart);
        //流程事件
        List<EventClass> procEventList=Optional.ofNullable(mapperManager.eventList(process_key))
                .orElseGet(()->iProcessDefinitionManager.createEventClass());
        params.setEventClass(procEventList);
        return params;
    }

    /**
     * 保存流程属性
     * @param processDefinitionParams
     * @return
     */
    @Override
    public String saveProcessProperties(ProcessDefinitionParams processDefinitionParams){
        OvProcessInstance ovProcessInstance=Optional.ofNullable(ovProcessInstanceMapper
                        .getProcessInsLastVersion(processDefinitionParams.getKey()))
                .orElseGet(()->iProcessDefinitionManager
                        .saveOvProcessInstance(processDefinitionParams.getKey(), processDefinitionParams));
        if(ovProcessInstance!=null){
            iProcessDefinitionManager.updateProcessProperties(processDefinitionParams);
        }
        return "保存成功";
    }

    /**
     * 获取节点属性
     * @param task_def_key
     * @return
     */
    @Override
    public TaskDefinitionParams userTaskProperties(String task_def_key){
        TaskDefinitionParams taskDefinitionParams=new TaskDefinitionParams();
        //节点基本信息
        FlowElementAttrs taskElementAttrs=mapperManager.getFlowElementAttrs(task_def_key);
        if(taskElementAttrs==null){
            return iProcessDefinitionManager.getTaskDefinitionParams(task_def_key);
        }
        else {
            TaskModel taskModel = new TaskModel();
            BeanUtils.copyProperties(taskElementAttrs, taskModel);
            //节点事件
            List<EventClass> eventList = Optional.ofNullable(mapperManager.eventList(task_def_key))
                    .orElseGet(() -> iProcessDefinitionManager.createEventClass());
            //逾期信息
            RuleOverDue ruleOverDue = Optional.ofNullable(mapperManager.ruleOverDue(task_def_key))
                    .orElseGet(() -> iProcessDefinitionManager.createRuleOverDue());
            taskDefinitionParams.setFormModel(taskModel);
            taskDefinitionParams.setRuleOverDue(ruleOverDue);
            taskDefinitionParams.setEventClass(eventList);
            taskDefinitionParams.setId(task_def_key);
            return taskDefinitionParams;
        }
    }

    /**
     * 保存节点属性
     * @param taskDefinitionParams
     * @return
     */
    @Override
    public String saveUserTaskProperties(TaskDefinitionParams taskDefinitionParams){
        //节点基本信息
        FlowElementAttrs taskElementAttrs=Optional.ofNullable(flowElementAttrsMapper
                .getFlowElementAttrs(taskDefinitionParams.getId()))
                .orElseGet(()->iProcessDefinitionManager
                        .saveFlowElementAttrs(taskDefinitionParams.getId(),taskDefinitionParams));
        if(taskElementAttrs!=null){
            BeanUtils.copyProperties(taskDefinitionParams.getFormModel(),taskElementAttrs);
            //节点基本信息
            TaskModel taskModel=taskDefinitionParams.getFormModel();
            BeanUtils.copyProperties(taskModel,taskElementAttrs);
            taskElementAttrs.setTask_def_key(taskDefinitionParams.getId());
            flowElementAttrsMapper.updateTaskAttrs(taskElementAttrs);

            //设置节点事件
            List<EventClass> taskEventClass=taskDefinitionParams.getEventClass();
            eventClassMapper.deleteEventClass(taskDefinitionParams.getId());
            List<EventClass> newTaskEventClass=new ArrayList<>();
            for(EventClass item:taskEventClass){
                item.setMypk(UUID.randomUUID().toString());
                item.setTargetId(taskDefinitionParams.getId());
                newTaskEventClass.add(item);
            }
            eventClassMapper.setEventClass(newTaskEventClass);

            //节点逾期设置
            RuleOverDue taskRuleOverDue=taskDefinitionParams.getRuleOverDue();
            taskRuleOverDue.setTargetId(taskDefinitionParams.getId());
            ruleOverDueMapper.deleteRuleOverDue(taskDefinitionParams.getId());
            taskRuleOverDue.setMypk(UUID.randomUUID().toString());
            ruleOverDueMapper.setRuleOverDue(taskRuleOverDue);
        }
        return "保存成功";
    }
    @Override
    public FlowElementAttrs getFlowElementAttrs(String task_def_id){
        FlowElementAttrs flowElementAttrs=flowElementAttrsMapper.getFlowElementAttrs(task_def_id);
        return flowElementAttrs;
    }
    @Override
    public List<FlowElementAttrs> getFlowElementFormAttrs(String process_key){
        List<FlowElementAttrs> flowElementAttrs=flowElementAttrsMapper.getFlowElementFormAttrs(process_key);
        return flowElementAttrs;
    }
    @Override
    public HashMap<String,Object> getFlowEnum(){
        List<FlowEnum> flowEnums=flowElementAttrsMapper.enumList();
        HashMap<String,Object> hashMap=new HashMap<>();

        List<HashMap<String,Object>> taskRuleList=new ArrayList<>();

        List<HashMap<String,Object>> returnWayList=new ArrayList<>();

        List<HashMap<String,Object>> jumpWayList=new ArrayList<>();

        List<HashMap<String,Object>> ccWayList=new ArrayList<>();

        List<HashMap<String,Object>> autoCCWayList=new ArrayList<>();

        List<HashMap<String,Object>> sexSelectList=new ArrayList<>();

        List<HashMap<String,Object>> userSatetList=new ArrayList<>();

        List<HashMap<String,Object>> startRulesList=new ArrayList<>();


        for(FlowEnum fe:flowEnums){
            if(fe.getRules().equals("taskRules")){
                HashMap<String,Object> taskRules=new HashMap<>();
                taskRules.put("ruleKey",fe.getKey());
                taskRules.put("taskRuleName",fe.getName());
                taskRuleList.add(taskRules);
            }
            else if(fe.getRules().equals("returnWay")){
                HashMap<String,Object> returnWay=new HashMap<>();
                returnWay.put("returnWayKey",fe.getKey());
                returnWay.put("returnWayName",fe.getName());
                returnWayList.add(returnWay);
            }
            else if(fe.getRules().equals("jumpWay")){
                HashMap<String,Object> jumpWay=new HashMap<>();
                jumpWay.put("jumpWayKey",fe.getKey());
                jumpWay.put("jumpWayName",fe.getName());
                jumpWayList.add(jumpWay);
            }
            else if(fe.getRules().equals("ccWay")){
                HashMap<String,Object> ccWay=new HashMap<>();
                ccWay.put("ccKey",fe.getKey());
                ccWay.put("ccName",fe.getName());
                ccWayList.add(ccWay);
            }
            else if(fe.getRules().equals("autoCCWay")){
                HashMap<String,Object> autoCCWay=new HashMap<>();
                autoCCWay.put("autoCCKey",fe.getKey());
                autoCCWay.put("autoCCName",fe.getName());
                autoCCWayList.add(autoCCWay);
            }
            else if(fe.getRules().equals("sexSelect")){
                HashMap<String,Object> sexSelect=new HashMap<>();
                sexSelect.put("value",fe.getKey());
                sexSelect.put("label",fe.getName());
                sexSelectList.add(sexSelect);
            }
            else if(fe.getRules().equals("userSatet")){
                HashMap<String,Object> userSatet=new HashMap<>();
                userSatet.put("value",fe.getKey());
                userSatet.put("label",fe.getName());
                userSatetList.add(userSatet);
            }
            else if(fe.getRules().equals("startRules")){
                HashMap<String,Object> startRules=new HashMap<>();
                startRules.put("ruleKey",fe.getKey());
                startRules.put("taskRuleName",fe.getName());
                startRulesList.add(startRules);
            }
        }
        hashMap.put("taskRules",taskRuleList);
        hashMap.put("returnWay",returnWayList);
        hashMap.put("jumpWay",jumpWayList);
        hashMap.put("ccWay",ccWayList);
        hashMap.put("autoCCWay",autoCCWayList);
        hashMap.put("sexSelect",sexSelectList);
        hashMap.put("userSatet",userSatetList);
        hashMap.put("startRules",startRulesList);
        return hashMap;
    }

    /**
     * 获取流程分类分页
     * @return
     */
    @Override
    public List<FlowSort> getFlowSort(){
        List<FlowSort> flowSortList= flowSortMapper.getFlowSort();
        return flowSortList;
    }

    /**
     * 获取流程树
     * @return
     */
    @Override
    public List<ProcessEntity> getFlowTree(){
        List<ProcessEntity> list=processEntityMapper.getFlowTree();
        return list;
    }
    /**
     * 获取全部流程分类树
     * @return
     */
    @Override
    public List<FlowSort> getFlowSortTree(){
        List<FlowSort> flowSortList= flowSortMapper.getFlowSort();
        //2、组装树形结构
        List<FlowSort> newList = flowSortList.stream()
                .filter(t -> t.getParentId() == 0)
                .map((menu) -> {
                    menu.setChildren(this.getChildren(menu,flowSortList));
                    return menu;
                })
                .collect(Collectors.toList());

        return newList;
    }
    @Override
    public HashMap getSatrtPageData(){
         HashMap map=new HashMap<>();
        List<HashMap<String,Object>> mapList=new ArrayList<>();
        List<FlowSort> flowSortList= flowSortMapper.getFlowSort();
        for(FlowSort fs:flowSortList){
            HashMap<String,Object> hashMap=new HashMap<>();
            hashMap.put("id",fs.getId());
            hashMap.put("name",fs.getName());

            List<FlowEntity> flowEntities=flowEntityMapper.getFlowListBySort(fs.getId().toString());

            if(flowEntities.size()>0){
                hashMap.put("flowList",flowEntities);
            }
            else{
                hashMap.put("flowList",new ArrayList<>());
            }
            mapList.add(hashMap);
        }
        map.put("flowList",mapList);

        return map;
    }

    /**
     * 获取常用流程
     * @return
     */
    @Override
    public List<FlowEntity> commProceList(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        List<FlowEntity> commProceList=flowEntityMapper.getCommProceList(username);
        return commProceList;
    }
    /**
     * 递归查找当前菜单的子菜单
     * @param root 单个对象
     * @param all 所有的集合
     * @return 排序后的子类
     */
    private List<FlowSort> getChildren(FlowSort root,List<FlowSort> all){
        List<FlowSort> childrenList = all.stream()
                .filter(t -> t.getParentId() == root.getId())
                .map(g -> {
                    //找子菜单
                    g.setChildren(getChildren(g,all));
                    return g;
                })
                //菜单排序
                .collect(Collectors.toList());

        return childrenList;
    }

    /**
     * 新增流程类别
     * @param flowSort
     * @return
     */
    @Override
    public String addFlowSort(FlowSort flowSort){
        if(!StringUtils.isNull(flowSort.getParentId())){
            flowSort.setParentId(Long.parseLong("0"));
        }
        int i=flowSortMapper.addFlowSort(flowSort);
        return "执行成功";
    }
    /**
     * 流程类别保存修改
     * @param flowSort
     * @return
     */
    @Override
    public String saveFlowSort(FlowSort flowSort){
        int i=flowSortMapper.saveFlowSort(flowSort);

        return "执行成功";
    }

    /**
     * 删除流程定义
     * @param deploymentId
     * @return
     */
    @Override
    public String deleteDefinition(String deploymentId){
        repositoryService.deleteDeployment(deploymentId, true);
        return "执行成功";
    }
    /**
     * 删除流程分类
     * @param flowSort
     * @return
     */
    @Override
    public String deleteFlowSort(FlowSort flowSort){
        int i=flowSortMapper.deleteFlowSort(flowSort);

        return "执行成功";
    }
}
